﻿using XiangziProjectTemplete.Core.Api.Common;
using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Utility;
using LesCCService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// 高压绕线线圈任务 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class Les_HighPressureProductsTaskController : ControllerBase
    {
        private readonly ILes_HighPressureProductsTaskServices _Les_HighPressureProductsTaskServices;
        private readonly IUser _user;
        private readonly ILogger<Les_HighPressureProductsTaskController> _logger;
        private readonly IV_HighPressureProductsTaskServices _v_HighPressureProductsTaskServices;
        private readonly IUserRoleServices _userRoleServices;

        public Les_HighPressureProductsTaskController(
             IUserRoleServices userRoleServices,
            IV_HighPressureProductsTaskServices v_HighPressureProductsTaskServices,
            ILes_HighPressureProductsTaskServices Les_HighPressureProductsTaskServices, IUser user, ILogger<Les_HighPressureProductsTaskController> logger)
        {
            this._userRoleServices = userRoleServices;
            _Les_HighPressureProductsTaskServices = Les_HighPressureProductsTaskServices;
            this._v_HighPressureProductsTaskServices = v_HighPressureProductsTaskServices;
            _user = user;
            _logger = logger;
        }

        /// <summary> 
        /// 分页获取高压绕线线圈任务列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        public async Task<MessageModel<PageModel<V_HighPressureProductsTask>>> Get([FromBody] V_HighPressureProductsTaskParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<V_HighPressureProductsTask, V_HighPressureProductsTaskParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<V_HighPressureProductsTask>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }

            //增加过滤 [EditBy shaocx,2021-10-06]
            if (param.LesTaskTypes != null && param.LesTaskTypes.Count > 0)
            {
                Expression<Func<V_HighPressureProductsTask, bool>> whereExpression2 = a => param.LesTaskTypes.Contains(a.LesTaskType);
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }

            #region 根据是否管理员进行过滤

            bool isManagerRole = await LesApiCommon.IsManagerRole(_userRoleServices, _user);
            if (isManagerRole == false)
            {
                Expression<Func<V_HighPressureProductsTask, bool>> whereExpression2 = a => a.CreateId == _user.ID;
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }

            #endregion


            var data = await _v_HighPressureProductsTaskServices.QueryPage(whereConditions.data, param.page, param.pageSize, " ModifyTime desc ");
            return new MessageModel<PageModel<V_HighPressureProductsTask>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };

        }

        /// <summary> 
        /// 获取单个高压绕线线圈任务 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<Les_HighPressureProductsTask>> Get(int id = 0)
        {
            return new MessageModel<Les_HighPressureProductsTask>()
            {
                msg = "获取成功",
                success = true,
                response = await _Les_HighPressureProductsTaskServices.QueryById(id)
            };
        }

        /// <summary> 
        /// 新增高压绕线线圈任务 
        /// </summary> 
        /// <param name="request">要新增的高压绕线线圈任务对象</param> 
        /// <returns></returns> 
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<bool>> Post([FromBody] Les_HighPressureProductsTask request)
        {
            try
            {
                #region 验证 
                MessageModel<bool> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Les_HighPressureProductsTask, bool>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                     new ValidateModel(){ ChinaName="XiangziProjectTemplete任务类型", DataType=typeof(int), DataValue=request.LesTaskType },
                     new ValidateModel(){ ChinaName="起始站点ID",DataType=typeof(int), DataValue=request.StationId  },
                };
                retBody = ValidateDataHelper.CommonValidate<Les_HighPressureProductsTask, bool>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }


                #region 验证用户是否登出

                var isUserLogout = LesApiCommon.IsUserLogout<bool>(_user);
                if (isUserLogout != null) return isUserLogout;

                #endregion


                #endregion

                request.Id = Guid.NewGuid().ToString();

                LesTaskTypeEnum lesTaskTypeEnum = (LesTaskTypeEnum)Enum.Parse(typeof(LesTaskTypeEnum), request.LesTaskType.ToString());
                switch (lesTaskTypeEnum)
                {
                    case LesTaskTypeEnum.高压内膜运送任务:
                        request.LesTaskNo = TaskNoHelper.GenerateLesTaskNo("HP_Mold");
                        break;
                    case LesTaskTypeEnum.高压绕线线圈运送任务:
                    case LesTaskTypeEnum.高压绕线线圈空车运送任务:
                        request.LesTaskNo = TaskNoHelper.GenerateLesTaskNo("HP_Coil");
                        break;
                    case LesTaskTypeEnum.低压线圈运送任务:
                    case LesTaskTypeEnum.低压线圈空车运送任务:
                        request.LesTaskNo = TaskNoHelper.GenerateLesTaskNo("LP_Coil");
                        break;
                    case LesTaskTypeEnum.低压内膜运送任务:
                        request.LesTaskNo = TaskNoHelper.GenerateLesTaskNo("LP_Mold");
                        break;
                    case LesTaskTypeEnum.自由搬运:
                        request.LesTaskNo = TaskNoHelper.GenerateLesTaskNo("FreeCarry");
                        break;
                    case LesTaskTypeEnum.高压装配线圈运送任务:
                    case LesTaskTypeEnum.高压装配线圈空车运送任务:
                        request.LesTaskNo = TaskNoHelper.GenerateLesTaskNo("HVcoil");
                        break;
                    case LesTaskTypeEnum.低压装配线圈运送任务:
                    case LesTaskTypeEnum.低压装配线圈空车运送任务:
                        request.LesTaskNo = TaskNoHelper.GenerateLesTaskNo("LVcoil");
                        break;
                    case LesTaskTypeEnum.低压脱模运送任务:
                        request.LesTaskNo = TaskNoHelper.GenerateLesTaskNo("LVDeMold");
                        break;
                    case LesTaskTypeEnum.高压脱模运送任务:
                        request.LesTaskNo = TaskNoHelper.GenerateLesTaskNo("HVDeMold");
                        break;
                }

                request.CreateTime = request.ModifyTime = DateTime.Now;
                request.CreateBy = request.ModifyBy = _user.Name;
                request.CreateId = request.ModifyId = _user.ID;
                request.OperationRemark = "添加";

                string requestStr = JsonConvert.SerializeObject(request);
                using (LesCCService.LesCCServiceClient client = new LesCCService.LesCCServiceClient())
                {
                    SdaResEntity sdaRes = null;
                    switch (lesTaskTypeEnum)
                    {
                        case LesTaskTypeEnum.高压内膜运送任务:
                            sdaRes = await client.CreateHighPressureMoldProductsTaskAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.高压绕线线圈运送任务:
                            sdaRes = await client.CreateHighPressureProductsTaskAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.高压绕线线圈空车运送任务:
                            sdaRes = await client.SetEmptyCarForHighPressureCoilAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.低压线圈运送任务:
                            sdaRes = await client.CreateLowPressureCoilProductsTaskAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.低压线圈空车运送任务:
                            sdaRes = await client.SetEmptyCarForLowPressureCoilAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.低压内膜运送任务:
                            sdaRes = await client.CreateLowPressureMoldProductsTaskAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.自由搬运:
                            sdaRes = await client.CreateMaterialCarryProductsTaskAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.高压装配线圈运送任务:
                            sdaRes = await client.CreateHVcoilProductsTaskAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.高压装配线圈空车运送任务:
                            sdaRes = await client.SetEmptyCarForHVcoilAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.低压装配线圈运送任务:
                            sdaRes = await client.CreateLVcoilProductsTaskAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.低压装配线圈空车运送任务:
                            sdaRes = await client.SetEmptyCarForLVcoilAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.低压脱模运送任务:
                            sdaRes = await client.CreateLowPressureDeMoldProductsTaskAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.高压脱模运送任务:
                            sdaRes = await client.CreateHighPressureDeMoldProductsTaskAsync(requestStr);
                            break;
                        case LesTaskTypeEnum.高压脱模空车任务:
                            sdaRes = await client.SetEmptyCarForHighPressureDeMoldLeadAsync(requestStr);
                            break;
                    }
                    if (sdaRes.resultk__BackingField)
                    {
                        return MessageModel<bool>.Success("成功");
                    }
                    else
                    {
                        return MessageModel<bool>.Fail(sdaRes.resMsgk__BackingField);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增任务出现异常:" + ex.Message);
                return MessageModel<bool>.Fail("新增任务出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 更新高压绕线线圈任务 
        /// </summary> 
        /// <param name="request">要更新的高压绕线线圈任务对象</param> 
        /// <returns>更新结果</returns> 
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] Les_HighPressureProductsTask request)
        {
            try
            {
                #region 验证 
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Les_HighPressureProductsTask, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>()
                {
                                         new ValidateModel(){ ChinaName="主键",PropertyName="Id" },
                     new ValidateModel(){ ChinaName="XiangziProjectTemplete任务号",PropertyName="LesTaskNo" },
                     new ValidateModel(){ ChinaName="生产任务号",PropertyName="BurdenWorkNo" },
                     new ValidateModel(){ ChinaName="任务状态",PropertyName="LesTaskStatus" },
                     new ValidateModel(){ ChinaName="任务状态",PropertyName="LesTaskStatusName" },
                     new ValidateModel(){ ChinaName="所属工序",PropertyName="AllowProcedure" },
                     new ValidateModel(){ ChinaName="起始站点ID",PropertyName="StationId" },
                     new ValidateModel(){ ChinaName="目标站点ID",PropertyName="ToStationId" },
                     new ValidateModel(){ ChinaName="货物类型",PropertyName="CargoType" },
                     new ValidateModel(){ ChinaName="下发时间",PropertyName="TaskIssueTime",DataType=typeof(DateTime),IsNullable=true },
                     new ValidateModel(){ ChinaName="完成时间",PropertyName="TaskFinishTime",DataType=typeof(DateTime),IsNullable=true },
                     new ValidateModel(){ ChinaName="人工处理时间",PropertyName="ManualHandlingTime",DataType=typeof(DateTime),IsNullable=true },

                };
                retBody = ValidateDataHelper.CommonValidate<Les_HighPressureProductsTask, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                #endregion

                var dbObj = await _Les_HighPressureProductsTaskServices.QueryById(request.Id);
                if (dbObj == null)
                {
                    return MessageModel<string>.Fail("数据不存在!");
                }

                request.ModifyTime = DateTime.Now;
                request.ModifyBy = _user.Name;
                request.ModifyId = _user.ID;
                request.OperationRemark = "更新";
                var success = await _Les_HighPressureProductsTaskServices.Update(request);

                if (success)
                {
                    return MessageModel<string>.Success("更新成功", request.Id.ObjToString());
                }
                return MessageModel<string>.Fail("更新失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新高压绕线线圈任务出现异常:" + ex.Message);
                return MessageModel<string>.Fail("更新高压绕线线圈任务出现异常:" + ex.Message);
            }
        }
    }
}
